﻿using log4net;
using Mangox.BLL.Mangox;
using Mangox.Common.Tookit;
using Mangox.Model.MangoxDB;
using MGXAPI.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web;
using System.Web.Http;

namespace MGXAPI.Controllers.API.Mangox
{
    public class AuthController : ApiController
    {
        protected static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected static string className = (new StackTrace()).GetFrame(1).GetMethod().ReflectedType.Name + "/";       //获取类名 
        Random rd = new Random();


        /// <summary>
        /// 获取用户信息API 多终端
        /// http://localhost:13772/api/Auth/Login?loginName=2068921&passWord=123456
        /// </summary>
        /// 登录名可以是UserID，LoginName，OpenID；手机号，邮箱登陆待确定
        /// 参数：{"LoginName":"liqiang","PassWord":"123456","Source":"0","IsData":"1"}
        /// <returns></returns>
        /// 密码应该只传入哈希
        /// *目前前端还未加入AppType
        [HttpPost]
        public LoginResultModel Login(LoginModel p)
        {
            LoginResultModel result = new LoginResultModel();
            result.Code = -1;

            log.Info(className + $"Login loginName-{p.LoginName}");
            try
            {
                if (string.IsNullOrWhiteSpace(p.LoginName))
                {
                    result.Msg = "用户名或账号不能为空";
                    return result;
                }

                if (string.IsNullOrWhiteSpace(p.PassWord))
                {
                    result.Msg = "密码不能为空";
                    return result;
                }

                //校验登陆
                MgxUserBLL bll = new MgxUserBLL();
                var u = bll.GetUser(p.LoginName, MgxCommBLL.GetUserPwd(p.PassWord));
                if (u != null)
                {
                    result.Code = 0;
                    result.Msg = "登陆成功";

                    if (p.IsData == "1")
                    {
                        result.Data = new M_UserResult();
                        ObjectReflection.AutoMapping(u, result.Data);
                    }

                    //Token字符串
                    result.Token = MgxCommBLL.CreateToken(u.UserID.ToString(), u.MgxHashID);

                    //写入session
                    //HttpContext.Current.Session["loginName"] = result.Token;

                    //读取session
                    //string loginName = HttpContext.Current.Session["loginName"] as string;
                }
                else
                {
                    result.Msg = "用户名或密码错误";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "登陆失败失败：" + ex.ToString();
                result.Data = null;
                log.Info(className + $"Login Fail-{ex.ToString()}");
            }
            return result;
        }


        /// <summary>
        /// 水龙头活动，不需要密码登陆，ERC地址登陆
        /// *创建和登陆在一起；如果已经存在就直接登陆
        /// http://localhost:13772/api/Auth/LoginSlt?ERCAddress=abcd
        /// </summary>
        /// 登录名可以是UserID，LoginName，OpenID；手机号，邮箱登陆待确定
        /// 参数：{"LoginName":"liqiang","PassWord":"123456","Source":"0","IsData":"1"}
        /// <returns></returns>
        /// 密码应该只传入哈希
        [HttpPost]
        public LoginResultModel LoginSlt(LoginModel p)
        {
            LoginResultModel result = new LoginResultModel();
            result.Code = -1;

            log.Info(className + $"LoginSlt loginName-{p.LoginName}");
            try
            {
                if (string.IsNullOrWhiteSpace(p.LoginName))
                {
                    result.Msg = "用户名或账号不能为空";
                    return result;
                }

                if (string.IsNullOrWhiteSpace(p.PassWord))
                {
                    result.Msg = "密码不能为空";
                    return result;
                }

                //校验登陆
                MgxUserBLL bll = new MgxUserBLL();
                var u = bll.GetUserSlt(p.LoginName, p.LoginName, (int)p.AppType);
                if (u != null)
                {
                    result.Code = 0;
                    result.Msg = "登陆成功";

                    if (p.IsData == "1")
                    {
                        result.Data = new M_UserResult();
                        ObjectReflection.AutoMapping(u, result.Data);
                    }

                    //Token字符串
                    result.Token = MgxCommBLL.CreateToken(u.UserID.ToString(), u.MgxHashID);

                    //写入session
                    //HttpContext.Current.Session["loginName"] = result.Token;

                    //读取session
                    //string loginName = HttpContext.Current.Session["loginName"] as string;
                }
                else
                {
                    result.Msg = "未找到此用户";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "登陆失败失败：" + ex.ToString();
                result.Data = null;
                log.Info(className + $"LoginSlt Fail-{ex.ToString()}");
            }
            return result;
        }


        #region 测试Session

        /// <summary>
        /// 先执行Get写入Session
        /// http://localhost:13772/api/Auth/get?id=1
        /// </summary>
        /// <returns></returns>
        public System.Collections.Generic.IEnumerable<string> Get()
        {
            var context = HttpContext.Current;
            context.Session["a"] = "aaa";
            return new string[] { "value1", "value2" };
        }

        /// <summary>
        /// 再获取session值
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string Get(int id)
        {
            var ses = HttpContext.Current.Session["a"];
            return ses.ToString();
        }

        #endregion


    }
}
